package com.seed.dev.web;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.seed.core.enumeration.YesNo;
import com.seed.core.pojo.LoginDTO;
import com.seed.core.pojo.R;
import com.seed.dev.web.user.User;
import com.seed.dev.web.user.UserService;
import com.seed.core.exception.UserAuthenticateException;
import com.seed.uaa.util.EncryptUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
public class LoginController {

    private UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @SaIgnore
    @PostMapping("login")
    public R<User> login(@RequestBody LoginDTO dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        User user = userService.getByUsername(username);
        if(user == null) throw new RuntimeException("用户不存在");
        if(user.getActive() != YesNo.yes) throw new RuntimeException("账号未激活");

        String reason = user.getReason();
        if(user.getEnable() != YesNo.yes) {
            String format = "用户账号【%s】被禁用，原因：【%s】";
            throw new RuntimeException(String.format(format, username, StrUtil.isBlank(reason) ? "无" : reason));
        }

        LocalDateTime expireDate = user.getExpireDate();
        if(expireDate != null && expireDate.isBefore(LocalDateTime.now())) {
            throw new RuntimeException(String.format("用户账号【%s】已过期", username));
        }

        if(!EncryptUtil.encrypt(password, user.getSalt()).equals(user.getPassword())) {
            throw new UserAuthenticateException("用户名或密码错误");
        }

        StpUtil.login(username);
        User ret = new User();
        ret.setId(user.getId());
        ret.setName(user.getName());
        ret.setAvatar(user.getAvatar());
        ret.setUsername(username);

        return R.data(ret);
    }

    @SaIgnore
    @GetMapping("logout")
    public R<String> logout() {
        StpUtil.logout();
        return R.ok("退出成功");
    }

    @SaIgnore
    @PostMapping("regist")
    public R<Boolean> regist(@RequestBody User registUser) {
        return R.data(userService.regist(registUser));
    }
}
